const logger = require('../console-logger')
const { doRequest } = require('../http-utils')

let apiKey = "";
let baseUrl = "https://api.themoviedb.org/3";
let proxy = null

function setup(setConfig) {
  // default
  apiKey = "";
  baseUrl = "https://api.themoviedb.org/3";
  proxy = null

  if (setConfig) {
    setConfig.apiKey && (apiKey = setConfig.apiKey);
    setConfig.host &&  (baseUrl = setConfig.host);
    if (setConfig.proxy) {
      // 判断时网络地址
      if (setConfig.proxy.match(/^(http|https|socks5):\/\//)) {
        const splited1 = setConfig.proxy.split(':\/\/');// ['socks5', '127.0.0.1:7890']
        const splited2 = splited1[1].split(':');// ['127.0.0.1', '7890']
        proxy = {
          protocol: splited1[0],
          host: splited2[0],
          port: splited2[1],
        }
      }
    }
  }
  if (!apiKey) {
    logger.info('TMDB apikey 未设置')
  } else {
    logger.info('TMDB 服务启动')
    proxy && logger.info('TMDB 启用代理', proxy)
  }
}

function call(options) {
  if (!apiKey)
    throw new Error('TMDB apikey 未设置');

  const requestOptions = {
    method: options.method || 'get',
    url: options.url,
    baseURL: baseUrl,
    // headers: {
    //   'Accept': 'application/json',
    //   'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.27'
    // },
    params: {
      api_key: apiKey,
      language: 'zh-CN', // en-US zh-CN
      ...options.params,
    },
    timeout: 30000,
  }
  if (proxy) {
    requestOptions.proxy = proxy;
  }
  if (options.data) {
    requestOptions.data = options.data 
  }
  return new Promise((resolve, reject) => {
    doRequest(requestOptions)
      .then(function (response) {
        resolve(response);
      })
      .catch(function (error) {
        // logger.error('doRequest error: ', error)
        reject(new Error(`TMDB API 请求失败: ${error.message}`));
      })
  });
}

const imageBaseUrl = 'https://image.tmdb.org/t/p/';

// 背景图片
const backdropImage = (url, size = 'default') => {
  if (size === 'default') {
    size = 'w780';
  } else if (size === 'small') {
    size = 'w300';
  } else if (size === 'medium') {
    size = 'w780';
  } else if (size === 'large') {
    size = 'w1280';
  } else {
    size = 'w780';
  }
  return `${imageBaseUrl}${size}${url}`;
};

// 封面图片
const posterImage = (url, size = 'default') => {
  if (size === 'default') {
    size = 'w342';
  } else if (size === 'small') {
    size = 'w154';
  } else if (size === 'medium') {
    size = 'w342';
  } else if (size === 'large') {
    size = 'w780';
  } else {
    size = 'w342';
  }
  return `${imageBaseUrl}${size}${url}`;
};

// 人员图 profile_sizes: [ 'w45', 'w185', 'h632', 'original' ],
const profileImage = (url, size = 'default') => {
  if (size === 'default') {
    size = 'w185';
  } else if (size === 'small') {
    size = 'w45';
  } else if (size === 'medium') {
    size = 'w185';
  } else if (size === 'large') {
    size = 'h632';
  } else {
    size = 'w185';
  }
  return `${imageBaseUrl}${size}${url}`;
};

// configuration
/*
{
  images: {
    base_url: 'http://image.tmdb.org/t/p/',
    secure_base_url: 'https://image.tmdb.org/t/p/',
    backdrop_sizes: [ 'w300', 'w780', 'w1280', 'original' ],
    logo_sizes: [ 'w45', 'w92', 'w154', 'w185', 'w300', 'w500', 'original' ],
    poster_sizes: [ 'w92', 'w154', 'w185', 'w342', 'w500', 'w780', 'original' ],
    profile_sizes: [ 'w45', 'w185', 'h632', 'original' ],
    still_sizes: [ 'w92', 'w185', 'w300', 'original' ]
  },
  change_keys: [
    'adult',                'air_date',         'also_known_as',
    'alternative_titles',   'biography',        'birthday',
    'budget',               'cast',             'certifications',
    'character_names',      'created_by',       'crew',
    'deathday',             'episode',          'episode_number',
    'episode_run_time',     'freebase_id',      'freebase_mid',
    'general',              'genres',           'guest_stars',
    'homepage',             'images',           'imdb_id',
    'languages',            'name',             'network',
    'origin_country',       'original_name',    'original_title',
    'overview',             'parts',            'place_of_birth',
    'plot_keywords',        'production_code',  'production_companies',
    'production_countries', 'releases',         'revenue',
    'runtime',              'season',           'season_number',
    'season_regular',       'spoken_languages', 'status',
    'tagline',              'title',            'translations',
    'tvdb_id',              'tvrage_id',        'type',
    'video',                'videos'
  ]
}
*/
const configuration = (type) => {
  // countries jobs languages primary_translations timezones
  let url = '/configuration';
  type && (url = `${url}/${type}`);
  return call({
    url,
  });
}

// mulit search
/*
{
  page: 1,
  results: [
    {
      backdrop_path: '/49IlZr2DH3407KwfL7i6RvWD1Mn.jpg',
      first_air_date: '2021-04-23',
      genre_ids: [Array],
      id: 124003,
      media_type: 'tv',
      name: '完美世界',
      origin_country: [Array],
      original_language: 'zh',
      original_name: '完美世界',
      overview: '　　《完美世界》动画改编自同名小说。他为修道而生，为应劫而至，他身化亿万血雨，洒落万古岁月，经历无数时空的熬炼，岁月长河的洗礼，他化万古，他化自在。看男主石昊如何一生极致辉煌，造就无尽传说。',
      popularity: 27.238,
      poster_path: '/eWGD5Zk9XhnlEncI2XP29qwfkUF.jpg',
      vote_average: 7.5,
      vote_count: 2
    },
    {
      backdrop_path: '/eNloCbtU2aillOoLYx0bRLmtGch.jpg',
      first_air_date: '2019-04-16',
      genre_ids: [Array],
      id: 88508,
      media_type: 'tv',
      name: '完美世界',
      origin_country: [Array],
      original_language: 'ja',
      original_name: 'パーフェクトワールド',
      overview: '本作改编自同名漫画《完美世界》。  　　因为遭遇事故而下身残疾，只能依靠轮椅生活的主人公鮎川樹（松坂桃李），在同学会上和高中同学川奈つぐみ（山本美月）再会。在心动之后，两人却要直面双亲的反对、疾病与伤痛、生活上的障碍、以及残疾所带来的并发症等等问题。  　　「究竟什么是幸福？」两人会做出怎样的选择呢？',
      popularity: 4.015,
      poster_path: '/mh3cXs75Si6h3I2zyNAeU7uSh0W.jpg',
      vote_average: 8.5,
      vote_count: 2
    },
    {
      adult: false,
      backdrop_path: '/gGBziIm4q9TsBeW7ibtkCcvnVhz.jpg',
      genre_ids: [Array],
      id: 546794,
      media_type: 'movie',
      original_language: 'ja',
      original_title: 'パーフェクトワールド 君といる奇跡',
      overview: '完美世界》是有贺理惠在讲谈社《KISS》上连载的漫画，讲述女白领与残疾建筑师之间的爱情故事。川奈亚美在学生时代的初恋是鲇川树，当川奈踏入社会并在室内装饰公司工作后，在饮酒会上重遇鲇川树，却发现他坐在轮椅上。原来鲇川树曾经历一场意外，导致不得不坐在轮椅上生活，而他目前是一名建筑师。就算对方是帅哥，残疾的话必然会对恋爱带来一定阻力。川奈在一番思想斗争后，还是决定要和鲇川树谈恋爱。',
      popularity: 4.263,
      poster_path: '/6SyUA5Oz9419TeoZk8Wq5dNtFkE.jpg',
      release_date: '2018-10-05',
      title: '完美世界',
      video: false,
      vote_average: 7.8,
      vote_count: 20
    },
    {
      backdrop_path: '/txEGR1MnJUGyat5rOjQorehL1Rh.jpg',
      first_air_date: '2000-02-25',
      genre_ids: [],
      id: 7120,
      media_type: 'tv',
      name: '完美世界',
      origin_country: [Array],
      original_language: 'en',
      original_name: 'Perfect World',
      overview: '《完美世界》是英国喜剧电视连续剧，于2000年2月25日至2001年6月25日在英国的BBC二台首次上映。围绕鲍勃·斯莱（Bob Slay）的生活展开，鲍勃·斯莱（Bob Slay）是业内领先的化妆品公司的营销主管，他令人讨厌，懒惰又不道德然，但鲍勃却有一个时髦的办公室和一个漂亮的女朋友，并受到他的经理的好评。',
      popularity: 1.739,
      poster_path: '/jNz0XEiDIt1t3BXQAsdlLkxjiq7.jpg',
      vote_average: 10,
      vote_count: 1
    },
    {
      adult: false,
      backdrop_path: '/3K54t5psPT0Ufqd2zbXK0sB4KUL.jpg',
      genre_ids: [Array],
      id: 9559,
      media_type: 'movie',
      original_language: 'en',
      original_title: 'A Perfect World',
      overview: '　　单亲孩子菲利普·佩里的母亲对他管教甚严，8岁的小菲利普甚至从未参加过一次鬼节讨糖果的游戏。附近州监狱的两名罪犯越狱成功，劫持了菲利普作为人质，向德州边界逃窜。途中，罪犯之一的布奇干掉了鲁莽愚蠢的同伙，却对小菲利普照顾有佳。与此同时，德州警探瑞德带着手下和州长特派的犯罪专家萨利一同火速追捕布奇。双方在德克萨斯州境内展开了一场公路赛大竞技；而小菲利普也经历了很多从未想过过的刺激与快乐，并与布奇产生了一种近似父子的不寻常感情……',
      popularity: 16.475,
      poster_path: '/1sUC7Oe3A0aXeLYO08nHWmzn5sO.jpg',
      release_date: '1993-11-24',
      title: '完美的世界',
      video: false,
      vote_average: 7.5,
      vote_count: 1313
    }
  ],
  total_pages: 1,
  total_results: 5
}
*/
const search = async (keyword) => {
  const res = await call({
    url: '/search/multi',
    params: {
      query: keyword
    }
  })
  return warpInfoList(res.results);
}

// movie search
const searchMovie = async (keyword, year) => {
  const res = await call({
    url: '/search/movie',
    params: {
      query: keyword,
      year: year
    }
  })
  return warpInfoList(res.results, 'movie');
}

// tv search
const searchTv = async (keyword, year) => {
  const res = await call({
    url: '/search/tv',
    params: {
      query: keyword,
      first_air_date_year: year
    }
  })
  return warpInfoList(res.results, 'tv');
}

// movie detail
/*
{
  adult: false,
  backdrop_path: '/vsTHSW1j3FDx3JTsiIfPcuu9C6h.jpg',
  belongs_to_collection: {
    id: 58588,
    name: '无间道（系列）',
    poster_path: '/ulSwmpjKTciBtNCJUqZg5knePp6.jpg',
    backdrop_path: '/ieW4mJg2C3HYBWSUM8lElbf9s6D.jpg'
  },
  budget: 250000,
  genres: [
    { id: 80, name: '犯罪' },
    { id: 18, name: '剧情' },
    { id: 28, name: '动作' }
  ],
  homepage: '',
  id: 14310,
  imdb_id: 'tt0374339',
  original_language: 'zh',
  original_title: '無間道III: 終極無間',
  overview: '刘建明在陈永仁被杀10个月后接受警队内部调查，被架空职权，加上家庭的变故，他的精神状态每况愈下，但他坚信局面很快就会扭转。年轻警司杨锦荣在同事看来是怪人一个，他正凭着过人的业绩迈向警队最高层。为了搞清楚杨锦荣的真实身份，刘建明开始对其调查。刘建明渐渐发现韩琛旧日的生意拍档沈澄与杨锦荣有着千丝万缕的关系，为了置杨锦荣于死地，也为了不让自己的身份曝光，渴望做个好人已久的刘建明开始千辛万苦地找寻一个又一个证据，可是他总在最接近真相时功亏一篑。',
  popularity: 11.281,
  poster_path: '/htg3GU5BQf2XRRAIXxOSlslwU6I.jpg',
  production_companies: [
    {
      id: 4713,
      logo_path: null,
      name: 'CMC Entertainment',
      origin_country: ''
    },
    {
      id: 5552,
      logo_path: '/wdtjT9x5OG7nLusPctACI3i7Im2.png',
      name: 'Media Asia Films',
      origin_country: 'HK'
    },
    {
      id: 14181,
      logo_path: null,
      name: 'Tianjin Film Studio',
      origin_country: ''
    },
    {
      id: 51470,
      logo_path: null,
      name: 'Basic Pictures',
      origin_country: ''
    },
    {
      id: 151304,
      logo_path: null,
      name: 'Eastern Dragon Film Co.',
      origin_country: ''
    }
  ],
  production_countries: [ { iso_3166_1: 'HK', name: 'Hong Kong' } ],
  release_date: '2003-12-12',
  revenue: 0,
  runtime: 118,
  spoken_languages: [
    { english_name: 'Cantonese', iso_639_1: 'cn', name: '广州话 / 廣州話' },
    { english_name: 'Thai', iso_639_1: 'th', name: 'ภาษาไทย' },
    { english_name: 'Mandarin', iso_639_1: 'zh', name: '普通话' }
  ],
  status: 'Released',
  tagline: '',
  title: '无间道3：终极无间',
  video: false,
  vote_average: 6.9,
  vote_count: 217
}
*/
const movieDetail = async (id) => {
  return warpInfoDetail(await call({
    url: `/movie/${id}`,
    params: {
      append_to_response: 'credits'
    }
  }), 'movie');
}
// tv detail
/*
{
  adult: false,
  backdrop_path: '/t5jnpVVWQBnl8B23bx3ijGCHt5L.jpg',
  created_by: [
    {
      id: 1760793,
      credit_id: '62e4bea68d2f8d005981ae8a',
      name: 'Jang Young-cheol',
      gender: 0,
      profile_path: null
    },
    {
      id: 2398176,
      credit_id: '62ea7b1ffc5f06006107e40b',
      name: 'Jung Gyeong-sun',
      gender: 0,
      profile_path: null
    }
  ],
  episode_run_time: [ 60 ],
  first_air_date: '2022-07-29',
  genres: [
    { id: 9648, name: '悬疑' },
    { id: 18, name: '剧情' },
    { id: 80, name: '犯罪' }
  ],
  homepage: 'https://program.imbc.com/BIGMOUTH',
  id: 155226,
  in_production: true,
  languages: [ 'ko' ],
  last_air_date: '2022-09-03',
  last_episode_to_air: {
    air_date: '2022-09-03',
    episode_number: 12,
    id: 3685973,
    name: '监狱暴动狱长欲杀昌浩',
    overview: '典狱长趁监狱因暴动而一片混乱时计划除掉昌浩和薇瑚。',
    production_code: '',
    runtime: 73,
    season_number: 1,
    show_id: 155226,
    still_path: '/vxYffZzZ3KsVkL8QIE9W4wwQS09.jpg',
    vote_average: 0,
    vote_count: 0
  },
  name: '绝命辩护',
  next_episode_to_air: {
    air_date: '2022-09-09',
    episode_number: 13,
    id: 3685975,
    name: '第 13 集',
    overview: '',
    production_code: '',
    runtime: null,
    season_number: 1,
    show_id: 155226,
    still_path: null,
    vote_average: 0,
    vote_count: 0
  },
  networks: [
    {
      id: 97,
      name: 'MBC',
      logo_path: '/pOSCKaZhndUFYtxHXjQOV6xJi1s.png',
      origin_country: 'KR'
    }
  ],
  number_of_episodes: 16,
  number_of_seasons: 1,
  origin_country: [ 'KR' ],
  original_language: 'ko',
  original_name: '빅마우스',
  overview: '一名官司胜率10%的生计型律师被卷入偶然承接的命案当中，一夕之间成了旷世天才诈骗犯“大老鼠”。为了保命并守护家人，他将揭发算计着滔天阴谋的特权阶层真面目。',
  popularity: 189.248,
  poster_path: '/2Vcj9LuWBQvNYSXyYSEEIM9071K.jpg',
  production_companies: [
    {
      id: 86418,
      logo_path: '/vzzqRwqTin3iAAMw2JlrmVPNnPa.png',
      name: 'Studio Dragon',
      origin_country: 'KR'
    },
    {
      id: 87422,
      logo_path: '/yipyNbVGcdyUtss9RtA4i7Zkkey.png',
      name: 'AStory',
      origin_country: 'KR'
    }
  ],
  production_countries: [ { iso_3166_1: 'KR', name: 'South Korea' } ],
  seasons: [
    {
      air_date: '2022-07-15',
      episode_count: 3,
      id: 302910,
      name: '特别篇',
      overview: '',
      poster_path: '/6aQGDOOqveiskP6ghBAJf5lO9Fo.jpg',
      season_number: 0
    },
    {
      air_date: '2022-07-29',
      episode_count: 16,
      id: 239232,
      name: '第 1 季',
      overview: '一名官司胜率10%的生计型律师被卷入偶然承接的命案当中。为了活命，他将与滔天阴谋正面对战。',
      poster_path: '/2Vcj9LuWBQvNYSXyYSEEIM9071K.jpg',
      season_number: 1
    }
  ],
  spoken_languages: [ { english_name: 'Korean', iso_639_1: 'ko', name: '한국어/조선말' } ],
  status: 'Returning Series',
  tagline: '',
  type: 'Scripted',
  vote_average: 8.5,
  vote_count: 22
}
*/
const tvDetail = async (id) => {
  return warpInfoDetail(await call({
    url: `/tv/${id}`,
    params: {
      append_to_response: 'credits'
    }
  }),'tv');
}
/*
{
  _id: '61dab7a5efea7a00426396c8',
  air_date: '2022-07-29',
  episodes: [
    {
      air_date: '2022-07-29',
      episode_number: 1,
      id: 3438017,
      name: '我会让你明白真正的绝望是什么滋味',
      overview: '被诈骗后，失去财产又深陷离婚危机的昌浩接到了九川市长崔道河的电话，请他承接牵涉到重量级人物的案件。',
      production_code: '',
      runtime: 63,
      season_number: 1,
      show_id: 155226,
      still_path: '/5niBVqToGQfJnyrocEFCVnzZNXh.jpg',
      vote_average: 6.667,
      vote_count: 3,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-07-30',
      episode_number: 2,
      id: 3685958,
      name: '你是大老鼠吗？',
      overview: '在医院里清醒过来的昌浩因涉嫌吸毒被关进九川监狱。但朴昌浩就是旷世天才诈骗犯大老鼠？',
      production_code: '',
      runtime: 74,
      season_number: 1,
      show_id: 155226,
      still_path: '/rQbLNhtFdbckse3hRIrF3lEk7WD.jpg',
      vote_average: 10,
      vote_count: 2,
      crew: [],
      guest_stars: [Array]
    },
    {
      air_date: '2022-08-05',
      episode_number: 3,
      id: 3685959,
      name: '别碰我老婆。一旦动手，所有人都会死...',
      overview: '究竟是谁出于什么原因让自己变成大老鼠？但他深知得让大众认为他是大老鼠才能保护薇瑚。',
      production_code: '',
      runtime: 72,
      season_number: 1,
      show_id: 155226,
      still_path: '/ltDgoW9awWqsZEiW3Q83Y4cgJvo.jpg',
      vote_average: 10,
      vote_count: 2,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-08-06',
      episode_number: 4,
      id: 3685962,
      name: '毒品交易名单...看来你很确定我不知道？',
      overview: '昌浩真的是大老鼠吗？孔之勋为了查出昌浩的真实身份而提议打赌。',
      production_code: '',
      runtime: 68,
      season_number: 1,
      show_id: 155226,
      still_path: '/8UUpJiWqbtVlqdcFJT8hQpqN0gn.jpg',
      vote_average: 10,
      vote_count: 1,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-08-12',
      episode_number: 5,
      id: 3685963,
      name: '我得动手了 按我的方式',
      overview: '之勋确信薇瑚握有徐才龙的论文并接近她。薇瑚知道朴昌浩的真实身份吗？还是她被蒙在鼓里呢？',
      production_code: '',
      runtime: 70,
      season_number: 1,
      show_id: 155226,
      still_path: '/sODSsR0SONrU5UvL9soG3Ndlbxh.jpg',
      vote_average: 10,
      vote_count: 1,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-08-13',
      episode_number: 6,
      id: 3685965,
      name: '你…真的是大老鼠吗？',
      overview: '昌浩会连薇瑚都隐瞒吗？薇瑚为了见昌浩一面，借着医疗志工活动前去监狱，昌浩在监狱里受到优待的样子让薇瑚感到很陌生。',
      production_code: '',
      runtime: 66,
      season_number: 1,
      show_id: 155226,
      still_path: '/9PYW4leA5yj4i2KGT0b1PxT4jka.jpg',
      vote_average: 10,
      vote_count: 1,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-08-19',
      episode_number: 7,
      id: 3685966,
      name: '开始打猎了',
      overview: '宰浩警告昌浩别想再探究徐才龙论文的事。离论文又更近一步的薇瑚被怪人袭击。',
      production_code: '',
      runtime: 71,
      season_number: 1,
      show_id: 155226,
      still_path: '/b0yF4kbZKP1IrNcVohkSMlLlxEA.jpg',
      vote_average: 0,
      vote_count: 0,
      crew: [],
      guest_stars: [Array]
    },
    {
      air_date: '2022-08-20',
      episode_number: 8,
      id: 3685968,
      name: '你知道隐藏谎言最完美的地方是哪里吗？',
      overview: '昌浩被监禁在精神病院。他能在精神恍惚的状态下隐藏好自己的真实身份吗？',
      production_code: '',
      runtime: 73,
      season_number: 1,
      show_id: 155226,
      still_path: '/vy9dOWgLEOE4bGf4OFUh9LlYe0e.jpg',
      vote_average: 0,
      vote_count: 0,
      crew: [],
      guest_stars: [Array]
    },
    {
      air_date: '2022-08-26',
      episode_number: 9,
      id: 3685969,
      name: '市长的局，昌浩的“锅”',
      overview: '昌浩通过社交媒体直播才能够以徐才龙命案的举报人身份站上法庭，此时之勋与仲乐也在追踪他。',
      production_code: '',
      runtime: 63,
      season_number: 1,
      show_id: 155226,
      still_path: '/kOsFVAob22hhHCKMLn5Qs7HjjjW.jpg',
      vote_average: 9,
      vote_count: 2,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-08-27',
      episode_number: 10,
      id: 3685971,
      name: '大老鼠另有其人',
      overview: '昌浩呼唤大老鼠，而对方回应了。令人意外的人物在约好的时间点出现。',
      production_code: '',
      runtime: 63,
      season_number: 1,
      show_id: 155226,
      still_path: '/q6abaakdqOPcccYu5zkinwLxeGc.jpg',
      vote_average: 9,
      vote_count: 1,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-09-02',
      episode_number: 11,
      id: 3685972,
      name: '监狱重新洗牌',
      overview: '昌浩让监狱里的权力版图重新洗牌，开始紧抓大老鼠的命脉。道河安插了新典狱长想找出大老鼠。',
      production_code: '',
      runtime: 72,
      season_number: 1,
      show_id: 155226,
      still_path: '/fnPd8Ksx4nv4qM8DCcgLBME9cCb.jpg',
      vote_average: 10,
      vote_count: 1,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-09-03',
      episode_number: 12,
      id: 3685973,
      name: '监狱暴动狱长欲杀昌浩',
      overview: '典狱长趁监狱因暴动而一片混乱时计划除掉昌浩和薇瑚。',
      production_code: '',
      runtime: 73,
      season_number: 1,
      show_id: 155226,
      still_path: '/vxYffZzZ3KsVkL8QIE9W4wwQS09.jpg',
      vote_average: 10,
      vote_count: 1,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-09-09',
      episode_number: 13,
      id: 3685975,
      name: '新大老鼠诞生',
      overview: '铁板料理餐厅成了一片废墟。慌忙的昌浩在重回那个地方时遇见了意想不到的人。',
      production_code: '',
      runtime: 64,
      season_number: 1,
      show_id: 155226,
      still_path: '/bjnM7gGVZpyyuopz106U7tvkGjy.jpg',
      vote_average: 9,
      vote_count: 1,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-09-10',
      episode_number: 14,
      id: 3685976,
      name: '帮我竞选市长怎么样？',
      overview: '昌浩前去拜访姜会长并提出能动摇他的提议，看不惯昌浩受瞩目的道河与尹甲联手计划除掉他。',
      production_code: '',
      runtime: 64,
      season_number: 1,
      show_id: 155226,
      still_path: '/mYehDX9rcRbWP0VlIpx2Pk7LCBs.jpg',
      vote_average: 0,
      vote_count: 0,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-09-16',
      episode_number: 15,
      id: 3685977,
      name: '第 15 集',
      overview: '当昌浩接受之勋的帮助，将正式展开选举之战时，薇瑚的健康却亮起红灯。',
      production_code: '',
      runtime: 70,
      season_number: 1,
      show_id: 155226,
      still_path: '/9Z4JoWTBfSy2pO8whozCsBOwZlX.jpg',
      vote_average: 10,
      vote_count: 1,
      crew: [],
      guest_stars: []
    },
    {
      air_date: '2022-09-17',
      episode_number: 16,
      id: 3685979,
      name: '第 16 集',
      overview: '',
      production_code: '',
      runtime: 71,
      season_number: 1,
      show_id: 155226,
      still_path: '/fAlPVaCmrC22KRUObtXgtTpaV71.jpg',
      vote_average: 0,
      vote_count: 0,
      crew: [],
      guest_stars: [Array]
    }
  ],
  name: '第 1 季',
  overview: '一名官司胜率10%的生计型律师被卷入偶然承接的命案当中。为了活命，他将与滔天阴谋正面对战。',
  id: 239232,
  poster_path: '/2Vcj9LuWBQvNYSXyYSEEIM9071K.jpg',
  season_number: 1
}
*/
const tvSeason = async (id, season=1) => {
  return await call({
    url: `/tv/${id}/season/${season}`
  });
}

const moviePopular = async (page=1) => {
  const res = await call({
    url: '/movie/popular',
    params: {
      page
    }
  }); 
  return warpInfoList(res.results, 'movie');
}

const tvPopular = async (page=1) => {
  const res = await call({
    url: '/tv/popular',
    params: {
      page
    }
  }); 
  return warpInfoList(res.results, 'tv');
}

const movieLatest = async () => {
  const res = await call({
    url: '/movie/latest',
    params: {
      page
    }
  }); 
  return warpInfoList(res.results, 'movie');
}

const tvLatest = async () => {
  const res = await call({
    url: '/tv/latest',
    params: {
      page
    }
  }); 
  return warpInfoList(res.results, 'tv');
}


const movieNowPlaying = async (page=1) => {
  const res = await call({
    url: '/movie/now_playing',
    params: {
      page
    }
  }); 
  return warpInfoList(res.results, 'movie');
}

const tvOnTheAir = async (page=1) => {
  const res = await call({
    url: '/tv/on_the_air',
    params: {
      page
    }
  }); 
  return warpInfoList(res.results, 'tv');
}

const movieGenre = () => {
  return call({
    url: '/genre/movie/list',
  });
}


const tvGenre = () => {
  return call({
    url: '/genre/tv/list',
  });
}

const warpInfo = (info, type) => {
  if (!info) return {};
  return  {
    id: info.id,
    title: info.title || info.name,
    original_title: info.original_title || info.original_name,
    year: info.release_date || info.first_air_date, // 2022-07-29
    poster: posterImage(info.poster_path), // 封面图
    backdrop: backdropImage(info.backdrop_path), // 背景图
    overview: info.overview, // 简介
    type: info.media_type || type, // movie, tv
    score: info.vote_average, // 7.8
    genre_ids: info.genre_ids, // 内容类型【1, 2, 3】
    original_language: info.original_language, // 语种 'en'
    origin_country: info.origin_country, // 国家/地区 ['US']
  }
}
const warpInfoList = (infoList, type) => {
  logger.debug('TMDB warpInfoList', infoList);
  if (!infoList || !infoList.length) return [];
  return infoList.map(info => warpInfo(info, type))
}



const warpInfoDetail = (info, type) => {
  logger.debug('TMDB warpInfoDetail', info);
  if (!info) return {};
  if (info.credits) {
    info.credits.profile_path_base = profileImage('');
  }
  return  {
    id: info.id,
    title: info.title || info.name,
    original_title: info.original_title || info.original_name,
    year: info.release_date || info.first_air_date, // 2022-07-29
    poster: posterImage(info.poster_path), // 封面图
    backdrop: backdropImage(info.backdrop_path), // 背景图
    overview: info.overview, // 简介
    type: info.media_type || type, // movie, tv
    score: info.vote_average, // 7.8
    genres: info.genres, // 内容类型
    original_language: info.original_language, // 语种 'en'
    origin_country: info.origin_country, // 国家/地区 ['US']
    status: info.status, // 状态 movie: Released, tv: Returning Series / Ended
    seasons: info.seasons, // 电视剧季数
    credits: info.credits, // 演职人员表
  }
}

module.exports = {
  setup, search, searchMovie, searchTv, movieDetail, tvDetail, tvSeason
  , moviePopular, tvPopular, movieLatest, tvLatest, movieNowPlaying, tvOnTheAir
  , movieGenre, tvGenre, configuration
  ,backdropImage, posterImage
}
